/*******************************************************************************
 * Copyright (c) 2010 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
/*
 * Created on 2005-3-31
 */
package com.luck.pf.util;

import java.io.Reader;
import java.sql.Clob;
import java.text.DecimalFormat;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;


public class ToolUtil {
	public final static int GBCODE = 1111;
    public final static int UNICODE = 2222;
    public final static String ISO8859_1="ISO8859_1";
    public final static String GBK="GBK";
    public final static String UTF8="UTF-8";
	public final static String CHARSET_ENCODING="GB2312";
	public final static String CONTENT_TYPE="text/xml;charset=gbk";
	public final static String CONTENT_TYPE_HTML="text/html;charset=gbk";
	
	public static String truncatChar (String url,String special){
		  if (url.startsWith(special)){
			  url = url.trim().substring(special.length());
		  }
		  return url ;
		}
	/**
	 * 判断字符是否为空
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str){
		if(str == null || str.equals(""))
			return true;
		str = str.trim();
		if(str == null || str.equals(""))
			return true;
		return false;
	}

	/**
	 * 移除指定字符
	 * @param resource
	 * @param ch
	 * @return
	 */
	public String removeChar(String resource,char ch)
    {
        StringBuffer buffer=new StringBuffer();
        int position=0;
        char currentChar;

        while(position<resource.length())
        {
            currentChar=resource.charAt(position++);
            if(currentChar!=ch)    buffer.append(currentChar);
        }
        return buffer.toString();
    }
	/**
	 * 格式化输出double(两位小位)
	 * @param putvalue
	 * @return
	 */
	public static Double formatDouble(Double putvalue){
		if(putvalue == null)
			return 0.00;
		DecimalFormat df = new DecimalFormat("#0.00");
		return new Double(df.format(putvalue));
	}
	/**
	 * 取指定长度字符串，后面加上...
	 * @param str
	 * @param size
	 * @return
	 */
	public static String substring(String str, int size){
    	int length = str.length();
    	if(length > size){
    		return str.substring(0, size)+"...";
    	}
    	return str;
    }
	/**
	 * 判断指定字符是否在父字符串中
	 * @param parent
	 * @param son
	 * @return
	 */
    public static boolean isInParentStr(String parent, String son){
		StringTokenizer tokenizer = new StringTokenizer(parent, ";");
		String roleId;
		while(tokenizer.hasMoreElements()){
			roleId = tokenizer.nextToken();
			if(roleId.equals(son))
				return true;
		}
    	return false;
    }
    /**
     * 将boolean转化为字符1,0
     * @param b
     * @return
     */
	public static String getBooleanAsString(boolean b) {
	    if (b)
	        return "1";
	    else
	        return "0";
	}
	/**
	 * 将1,0字符转化为boolean
	 * @param b
	 * @return
	 */
	public static boolean getStringAsBoolean(String b) {
	    if (b == null || b.equals("") || !b.equals("1"))
	        return false;
	    else
	        return true;
	}
	/**
	 * 将String转化为Long
	 * @param str
	 * @return
	 */
	public static Long strToLong(String str){
		Long l = new Long(0);
		if(isEmpty(str))
			return l;
		str = str.trim();
		try {
			 l = new Long(str); 
		} catch (Exception e) {
			l = new Long(0);
		}
		return l;
	}
	/**
	 * 将String转化为Integer
	 * @param str
	 * @return
	 */
	public static Integer strToInteger(String str){
		Integer l = 0;
		if(isEmpty(str))
			return l;
		str = str.trim();
		try {
			 l = new Integer(str); 
		} catch (Exception e) {
			l = 0;
		}
		return l;
	}
	/**
	 * 将String转化为Double
	 * @param str
	 * @return
	 */
	public static Double strToDouble(String str){
		Double d = 0.00;
		if(isEmpty(str))
			return 0.00;
		try {
			str = str.trim();
			d = new Double(str);
		} catch (Exception e) {
			d = 0.00;
		}
		return d;
	}
	/**
	 * 是否是字符
	 * @param c
	 * @return
	 */
	public static boolean isLetter(char c) {
		int k = 0x80;
		return c / k == 0 ? true : false;
	}

	/**
	 * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
	 * 
	 * @param String
	 *            s ,需要得到长度的字符串
	 * @return int, 得到的字符串长度
	 * @throws Exception 
	 */
	public static int length(String str) throws Exception{
		if(isEmpty(str))
			return 0;
		byte[] b = str.getBytes("GBK");
		return b.length;
	}

	/**
	 * @param start 开始位数(包括开始位数start值)
	 * @param size 截取位数(不包括结束位数start+size值)
	 * @param encode 编码
	 */
	public static String substring(String str, int start, int size, String encode)
			throws Exception {
		if(isEmpty(encode))
			encode="GBK";
		if (isEmpty(str))
			return "";
		byte[] b = str.getBytes(encode);
		if((start+size)>b.length)
			size = b.length-start;
		if(size<=0)
			return "";
		return new String(b,start,size,encode);
	}
	/**
	 * 将全角转为半角
	 * @param QJstr
	 * @return
	 */
	public static String Q2B(String QJstr) {// 全角-->半角
        String outStr = "";
        String Tstr = "";
        byte[] b = null;
       
        for (int i = 0; i < QJstr.length(); i++) {
            try {
                Tstr = QJstr.substring(i, i + 1);
                b = Tstr.getBytes("unicode");
            } catch (java.io.UnsupportedEncodingException e) {
                e.printStackTrace();
            }
           
            if (b[3] == -1) {
                b[2] = (byte) (b[2] + 32);
                b[3] = 0;
               
                try {
                    outStr = outStr + new String(b, "unicode");
                } catch (java.io.UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else
                outStr = outStr + Tstr;
        }
        return outStr;
    }
	/**
	 * 将全半角转为角
	 * @param QJstr
	 * @return
	 */
	public static String B2Q(String QJstr){// 半角-->全角
        String outStr = "";
        String Tstr = "";
        byte[] b = null;
       
        for (int i = 0; i < QJstr.length(); i++) {
            try {
                Tstr = QJstr.substring(i, i + 1);
                b = Tstr.getBytes("unicode");
            } catch (java.io.UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (b[3] == 0) {
                b[2] = (byte) (b[2] - 32);
                b[3] = -1;
               
                try {
                    outStr = outStr + new String(b, "unicode");
                } catch (java.io.UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else
                outStr = outStr + Tstr;
        }
       
        return outStr;
    }
	/**
	 * 取得当前IP地址
	 * @param request
	 * @return
	 */
	 public static String getIpAddr(HttpServletRequest request) {  
	     String ip = request.getHeader("x-forwarded-for");  
	     if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	         ip = request.getHeader("Proxy-Client-IP");  
	     }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	         ip = request.getHeader("WL-Proxy-Client-IP");  
	     }  
	     if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	         ip = request.getRemoteAddr();  
	     }  
	     return ip;  
	}  
	 /**
	  * 将clob转换成string
	  * @param clob
	  * @return
	  */
	 public final static String clob2String(Clob clob) {
			if (clob == null) {
				return null;
			}
			StringBuffer sb = new StringBuffer(65535);// 64K
			Reader clobStream = null;
			try {
				clobStream = clob.getCharacterStream();
				char[] b = new char[60000];// 每次获取60K
				int i = 0;
				while ((i = clobStream.read(b)) != -1) {
					sb.append(b, 0, i);
				}
			} catch (Exception ex) {
				sb = null;
			} finally {
				try {
					if (clobStream != null)
						clobStream.close();
				} catch (Exception e) {
				}
			}
			if (sb == null)
				return null;
			else
				return sb.toString();
		}
	 public static String filterAreaContent(String content){
		 if(StringUtils.isBlank(content))
			 return "";
		 content = content.replace("\n", "<br/>");
		 content = content.replace("\r", "<br/>");
		 content = content.replace(" ", "&nbsp;");
		 return content;
	 }
	 /**
	  * 得到当前项目根目录
	  * @return
	  * @throws Exception
	  */
	 public static String getWebRootPath() throws Exception{
		 String path = ToolUtil.class.getResource("/").getPath();
	     int size = path.indexOf("WEB-INF");
	     return path.substring(1,size);
	 }
}